//
//  TKIMToolView.m
//  TKIM
//
//  Created by liupm on 15/10/16.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMToolView.h"
//#import "TKIMUIHelper.h"
#import "TKIMLocationViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import "AssetsLibrary/AssetsLibrary.h"
//#import "TKIMImageMessage.h"
//#import "TKIMVideoMessage.h"
//#import "TKIMFileHelper.h"
#import "TKIMLayerUtils.h"

@interface TKIMToolView()<TKIMLocationViewControllerDelegate,UIImagePickerControllerDelegate>
@property (strong ,nonatomic) AVPlayer *player;//播放器，用于录制完视频后播放视频
@property (assign,nonatomic) int isVideo;//是否录制视频，如果为1表示录制视频，0代表拍照
@property (strong,nonatomic) UIImagePickerController *imagePicker;
@property(nonatomic,weak)  UIViewController *currentController;
@property(nonatomic,assign) BOOL isNeedPhoto;
@property(nonatomic,assign) BOOL isNeedQuick;
@end

@implementation TKIMToolView
{
    NSMutableArray *_dataArray;
}


-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.row = 2;
        self.cloum =4;
        [self initData];
        _isNeedPhoto = YES;
    }
    return self;
}

-(instancetype)initNoNeedPhotoWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self)
    {
        self.row = 2;
        self.cloum =4;
        _currentController = [TKIMUIHelper getCurrentVC];
        _dataArray = [self getConfigDataByKey:@"tool"];
        [_dataArray removeObjectAtIndex:0];
        [_dataArray removeObjectAtIndex:0];
        [self drawView:_dataArray];
        _isNeedPhoto = NO;
    }
    return self;
}

-(instancetype)initNoNeedQuickWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self)
    {
        _isNeedQuick = NO;
        self.row = 2;
        self.cloum =4;
        _currentController = [TKIMUIHelper getCurrentVC];
        _dataArray = [self getConfigDataByKey:@"tool"];
        [_dataArray removeLastObject];
        [self drawView:_dataArray];
    }
    return self;
}

/**
 *  @Author lpm, 15-08-03 14:08:18
 *
 *  @brief 初始化表情数据
 */
-(void)initData
{
    _currentController = [TKIMUIHelper getCurrentVC];
    _dataArray = [self getConfigDataByKey:@"tool"];
    [self drawView:_dataArray];
}


/**
 *  @Author lpm, 15-08-03 16:08:19
 *
 *  @brief  获得子元素
 *
 */
-(UIView *)getItem:(NSMutableDictionary *)data frame:(CGRect)rect
{
    UIView *view = [[UIView alloc] initWithFrame:rect];
    NSString *imgUrl = data[@"value"];
    UIImage *image = TKIMGetImage(imgUrl);
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(rect.size.width*0.2, 3, rect.size.width*0.65, rect.size.width*0.65)];
    [button setImage:image forState:UIControlStateNormal];
    button.backgroundColor = [UIColor clearColor];
    button.userInteractionEnabled = NO;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, button.frame.size.height+button.frame.origin.y+5, rect.size.width, rect.size.height*0.3)];
    label.font = [UIFont systemFontOfSize:13.0f];
    label.textColor = [UIColor grayColor];
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor clearColor];
    label.text = data[@"key"];
    
    [view addSubview:label];
    [view addSubview:button];
    
    return view;
}


/**
 *  @Author lpm, 15-08-03 16:08:19
 *
 *  @brief  子元素被点击
 *
 */
-(void)item:(UIView *)view didSelected:(NSInteger)index
{
    if (_isNeedPhoto||!_isNeedQuick) {
        if (index == 0)
        {
            // 创建控制器
            TKIMImagePickerViewController *pickerVc = [[TKIMImagePickerViewController alloc] init];
            // 默认显示相册里面的内容SavePhotos
            pickerVc.maxAllowSelect = 5;
            __weak typeof(self) weakSelf = self;
            pickerVc.imageCallBck = ^(NSArray *assets)
            {
                [weakSelf routerEventWithName:TKIMImageSelectedEvent userInfo:assets];
            };
            [[TKIMUIHelper getCurrentVC] presentViewController:pickerVc animated:YES completion:nil];
        }
        else if (index == 2)
        {
            [self routerEventWithName:TKIMSendQuickReplyEvent userInfo:nil];
        }
        else if (index == 3)
        {
            if(![self AVAuthorizationStatu])
            {
                return;
            }
            //通过这里设置时拍照还是录制视频
            _isVideo=YES;
            [_currentController presentViewController:self.imagePicker animated:YES completion:nil];
        }
        else if(index == 1)
        {
            if(![self AVAuthorizationStatu])
            {
                return;
            }
            //通过这里设置时拍照还是录制视频
            _isVideo=NO;
            [_currentController presentViewController:self.imagePicker animated:YES completion:nil];
        }
        else if(index == 4)
        {
            [self routerEventWithName:TKIMAudioChatSelectedEvent userInfo:nil];
        }
        else if(index == 5)
        {
            [self routerEventWithName:TKIMVideoChatSelectedEvent userInfo:nil];
        }

    }else{
        if (index == 0)
        {
            [self routerEventWithName:TKIMSendQuickReplyEvent userInfo:nil];
        }
    }
}



-(BOOL)AVAuthorizationStatu
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied||![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
    {
        
        if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0"] != NSOrderedAscending)
        {
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要启用您的相机\n请启用相机-设置/隐私/相机" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert show];
        }
        else
        {
            UIAlertView *alert  = [[UIAlertView alloc] initWithTitle:@"提示" message:@"需要启用您的相机\n请启用相机-设置/隐私/相机" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
            [alert show];
        }
        return NO;
    }
    return YES;
}




- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[[UIDevice currentDevice] systemVersion] compare:@"8.0"] != NSOrderedAscending)
    {
        if (buttonIndex == 1)
        {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
    }
}


#pragma mark - UIImagePickerController代理方法

/**
 *  @Author lpm, 15-10-27 19:10:54
 *
 *  @brief  拍照或录制完成
 *
 *  @param picker
 *  @param info
 */
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {//如果时拍照
        UIImage *image;
        //如果允许编辑则获得编辑后的照片，否则获取原始照片
        if (self.imagePicker.allowsEditing)
        {
            //获取编辑后的照片
            image=[info objectForKey:UIImagePickerControllerEditedImage];
        }
        else
        {
            //获取原始照片
            image=[info objectForKey:UIImagePickerControllerOriginalImage];
        }
        //图片保存成功失败的回调
        ALAssetsLibraryWriteImageCompletionBlock completeBlock = ^(NSURL *assetURL, NSError *error)
        {
            //图片保存成功
            if (!error)
            {
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    TKIMImageMessage *imgMsg = [[TKIMImageMessage alloc] init];
                    imgMsg.originImage = [info objectForKey:UIImagePickerControllerOriginalImage];
                    imgMsg.thumbImage = [UIImage imageWithData:UIImageJPEGRepresentation(image, 0.6)] ;
                    imgMsg.isSender = YES;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self routerEventWithName:TKIMSendPhotoEvent userInfo:imgMsg];
                    });
                });
            }
        };
        
        //如果图片存在则保存图片
        if(image)
        {
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library writeImageToSavedPhotosAlbum:[image CGImage]
                                      orientation:(ALAssetOrientation)[image imageOrientation]
                                  completionBlock:completeBlock];
        }
        [_currentController dismissViewControllerAnimated:YES completion:nil];
    }
    //如果是录制视频
    else if([mediaType isEqualToString:(NSString *)kUTTypeMovie])
    {
        TKIMVideoMessage *msg = [[TKIMVideoMessage alloc] init];
        msg.isEncoding = YES;
        msg.isSender = YES;
        //视频路径
        NSURL *url=[info objectForKey:UIImagePickerControllerMediaURL];
        NSString *urlStr=[url path];
        
        [[TKIMLayerUtils instance] showLoading:YES withLabel:@"视频编码中"];
        
        [TKIMFileHelper convert2Mp4:url complete:^(NSURL *mp4Url)
         {
             [[TKIMLayerUtils instance] showLoading:NO];
             [_currentController dismissViewControllerAnimated:YES completion:nil];
             if (mp4Url)
             {
                 NSFileManager *fileman = [NSFileManager defaultManager];
                 if ([fileman fileExistsAtPath:urlStr]) {
                     NSError *error = nil;
                     [fileman removeItemAtURL:url error:&error];
                     if (error) {
                         NSLog(@"failed to remove file, error:%@.", error);
                     }
                 }
                 msg.localUrl = [TKIMFileHelper moveFile:mp4Url.relativePath fileName:msg.fileName];
                 
                 [self routerEventWithName:TKIMVideoSelectedEvent userInfo:msg];
             }
         }];
    }
    self.imagePicker = nil;
    
    
}



/**
 *  @Author lpm, 15-10-27 19:10:18
 *
 *  @brief  取消拍照或者录制
 *
 *  @param picker
 */
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    NSLog(@"取消");
    [_currentController dismissViewControllerAnimated:YES completion:nil];
    self.imagePicker = nil;
}



#pragma mark - 私有方法
-(UIImagePickerController *)imagePicker
{
    if (!_imagePicker)
    {
        _imagePicker=[[UIImagePickerController alloc]init];
        //设置image picker的来源，这里设置为摄像头
        _imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        //设置使用哪个摄像头，这里设置为后置摄像头
        _imagePicker.cameraDevice=UIImagePickerControllerCameraDeviceRear;
        if (self.isVideo) {
            _imagePicker.mediaTypes=@[(NSString *)kUTTypeMovie];
            _imagePicker.videoQuality=UIImagePickerControllerQualityTypeMedium;
            //设置摄像头模式（拍照，录制视频）
            _imagePicker.cameraCaptureMode=UIImagePickerControllerCameraCaptureModeVideo;
            [_imagePicker  setVideoMaximumDuration:20];
            
        }else{
            _imagePicker.cameraCaptureMode=UIImagePickerControllerCameraCaptureModePhoto;
        }
        _imagePicker.allowsEditing=NO;//允许编辑
        _imagePicker.delegate=self;//设置代理，检测操作
        _imagePicker.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    }
    return _imagePicker;
}


/**
 *  @Author lpm, 15-10-27 19:10:32
 *
 *  @brief  视频保存后的回调
 *
 *  @param videoPath
 *  @param error
 *  @param contextInfo
 */
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error)
    {
        NSLog(@"保存视频过程中发生错误，错误信息:%@",error.localizedDescription);
    }else
    {
        NSLog(@"视频保存成功.");
    }
}


/**
 *  @Author lpm, 15-10-27 19:10:52
 *
 *  @brief  图片保存后回调
 *
 *  @param image
 *  @param error
 *  @param contextInfo
 */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error )
    {
        NSLog(@"图片保存成功.");
    }
}


-(void)dealloc
{
}

@end
